package com.bodacn.andontv;


import android.animation.ArgbEvaluator;
import android.animation.ObjectAnimator;
import android.animation.ValueAnimator;
import android.app.ProgressDialog;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.speech.tts.TextToSpeech;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.text.DecimalFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;
import java.util.regex.Matcher;
import java.util.regex.Pattern;


public class AndonFragment extends Fragment implements View.OnClickListener {
    // TODO: Rename parameter arguments, choose names that match
    private final static String TAG = AndonFragment.class.getSimpleName();
    private final static int MSG_Refresh=1001;
    private static String RunState="TRUE";
    //用于与主Activity通讯;
    private Handler mainHandler;
    private ProgressDialog waitDialog = null;
    TextToSpeech textToSpeech;
    //初始化定时器;
    private Timer timer;
    private TimerTask timetask;
    private static int runCount=0;//计数器，超过一定的次数，就刷新数据;
    //全局变量
    SQLiteDatabase tmpdb;
    //分页显示;
    private JSONArray CallList;//用于存储WebService返回的结果;
    private int totalItemCount=10,pageCount=0,curPage=0;
    private static final int pageItemCount = 6;//每页显示内容;
    //媒体播放文件
    private static MediaPlayer mediaPlayer;
    //置值
    private static boolean firstLoad=false;
    static Drawable drawable_itemA,drawable_itemB;
    //数据内容
    ListView lv_andon;
    ImageView img_Card;
    TextView tv_CardCallNo,tv_CardCallState;
    JSONArray myJsonArray;
    String ServiceDir,ServiceUrl,PushTime;
    int SwitchCount,SpaceSec;
    String CurCallNo="---",CurFontColor="#FFFFFF",CurCallState="";

    public AndonFragment() {
        // Required empty public constructor
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //创建对话框，
        waitDialog=new ProgressDialog(getContext());
        waitDialog.setTitle("请稍等");
        waitDialog.setIndeterminate(true);
        //得到Activity的Handler,用于发消息给主Activity;
        MainActivity activity=(MainActivity) getActivity();
        mainHandler=activity.mainHandler;
        //加接口监听
        activity.setTransAndonParamsListener(new MainActivity.OnTransAndonParamsListener() {
            @Override
            public void TransParams(Map<String, Object> mParams) {
                if (mParams!=null) {
                    try {
                        Log.d(TAG,"setTransAndonParamsListener----TransParams--1");
                        String paramComm= mParams.get("ParamComm").toString();
                        //根据参数显示订单信息;
                        if (paramComm=="ParamValue")
                        {
                            Log.d(TAG,"ParamValue------------------>1");
                            ServiceUrl=mParams.get("ServiceUrl").toString();
                            ServiceDir=mParams.get("ServiceDir").toString();
                            PushTime=mParams.get("PushTime").toString();
                            SpaceSec=Integer.valueOf(mParams.get("SpaceSec").toString());
                            SwitchCount=Integer.valueOf(mParams.get("SwitchCount").toString());
                            //传递登陆参数信息;
                            RunState=mParams.get("RunState").toString();
                            startTimer();
                            Log.d(TAG,"ParamValue------------------>2");
                        }
                        if (paramComm=="TTS")
                        {
                            Log.d(TAG,"TTS------------------>1");
                            try {
                                stopTimer();
                                String paramText = mParams.get("ParamText").toString();
                                textToSpeech.speak(paramText, TextToSpeech.QUEUE_ADD, null);
                                startTimer();
                            } catch (Exception e){
                                //Toast.makeText(getContext(),e.getMessage(),Toast.LENGTH_LONG).show();
                            }
                            Log.d(TAG,"TTS------------------>2");
                        }
                        Log.d(TAG,"setTransAndonParamsListener----TransParams--2");
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        });
        //取背景;
        drawable_itemA = getResources().getDrawable(R.drawable.andon_itema_back);
        drawable_itemB = getResources().getDrawable(R.drawable.andon_itemb_back);
    }


    //实现语音初始化构造函数
    private class TTSListener implements TextToSpeech.OnInitListener {
        @Override
        public void onInit(int status) {
            // TODO Auto-generated method stub
            if (status == TextToSpeech.SUCCESS) {
                Log.i(TAG, "onInit: TTS引擎初始化成功");
            }
            else{
                Log.i(TAG, "onInit: TTS引擎初始化失败");
            }
        }
    }

    //打开数据库
    public void OpenCreateDB(){
        if (tmpdb==null) {
            MainActivity activity = (MainActivity) getActivity();
            tmpdb = activity.mainDB;
        }
    }
    //加载安东列表
    private void GetCallList() {
        boolean loadSign=false;
        String callText="";
        CurCallNo="---";
        CurFontColor="#FFFFFF";
        CurCallState="";
        boolean needPlay=false;
        Log.e(TAG,"GetCallList()-----------------------Start");
        if (tmpdb==null) OpenCreateDB();
        if (tmpdb!=null) {
            try {
                CallList = new JSONArray("[]");
            } catch (JSONException e) {
                e.printStackTrace();
            }
            Cursor cur = tmpdb.rawQuery("Select * from CallList where CallState<2 Order by CallState,CASE WHEN CallType =\"维修\"  THEN 0 ELSE 1 END,CallTime", null);
            if (cur.getCount()>0)
            {
                while (cur.moveToNext()) {
                    JSONObject objectJSON = new JSONObject();
                    try {
                        if (loadSign==false){
                            loadSign=true;
                            CurCallNo=cur.getString(cur.getColumnIndex("CallNo"));
                            CurCallState=cur.getString(cur.getColumnIndex("StateInfo"));
                            CurFontColor=cur.getString(cur.getColumnIndex("FontColor"));
                        }

                        if (cur.getInt(cur.getColumnIndex("CallState"))<1) needPlay=true;
                        objectJSON.put("CallID", cur.getString(cur.getColumnIndex("CallID")));
                        objectJSON.put("CallTime", cur.getString(cur.getColumnIndex("CallTime")));
                        objectJSON.put("CallNo", cur.getString(cur.getColumnIndex("CallNo")));
                        objectJSON.put("CallAddr", cur.getString(cur.getColumnIndex("CallAddr")));
                        objectJSON.put("EmpName", cur.getString(cur.getColumnIndex("EmpName")));
                        if (cur.getString(cur.getColumnIndex("CallType")).equals("维修")==false)
                            callText=cur.getString(cur.getColumnIndex("EmpName"))+"呼叫"+cur.getString(cur.getColumnIndex("CallType"));
                        objectJSON.put("CallType", cur.getString(cur.getColumnIndex("CallType")));
                        objectJSON.put("CheckTime", cur.getString(cur.getColumnIndex("CheckTime")));
                        objectJSON.put("OverTime", cur.getString(cur.getColumnIndex("OverTime")));
                        objectJSON.put("CallState", cur.getInt(cur.getColumnIndex("CallState")));
                        objectJSON.put("StateInfo", cur.getString(cur.getColumnIndex("StateInfo")));
                        objectJSON.put("UpLoad", cur.getInt(cur.getColumnIndex("UpLoad")));
                        objectJSON.put("CallColor", cur.getString(cur.getColumnIndex("CallColor")));
                        objectJSON.put("FontColor", cur.getString(cur.getColumnIndex("FontColor")));
                        objectJSON.put("NeedCheck", cur.getString(cur.getColumnIndex("NeedCheck")));
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                    CallList.put(objectJSON);
                }
            }
            cur.close();
        }
        //播放音乐!
        if (needPlay==true) {
            System.out.println("callText");
            if (callText.length()>0) textToSpeech.speak(callText,TextToSpeech.QUEUE_ADD,null);
            else playMusic("andon.mp3");
        }
        else stopMusic();
    }

    //设定当前状态卡片颜色;
    private void setCardState(String paramColor,String paramCallNo,String paramCallState){
        int duration=500;
        if (paramColor.indexOf("#")<0) paramColor="#"+paramColor;
        int colorA=GetColorValue(paramColor);
        int colorB=colorA;
        System.out.println("D");
        int colorC=Color.parseColor("#00"+paramColor.substring(1));
        System.out.println("E");
        tv_CardCallNo.setText(paramCallNo);
        tv_CardCallNo.setTextColor(colorA);
        tv_CardCallState.setText(paramCallState);
        tv_CardCallState.setTextColor(colorA);
        ObjectAnimator objectAnimator = ObjectAnimator.ofInt(img_Card,"backgroundColor",colorA,colorB,colorC);
        objectAnimator.setDuration(duration);
        objectAnimator.setEvaluator(new ArgbEvaluator());
        objectAnimator.setRepeatCount(ValueAnimator.INFINITE);
        objectAnimator.setRepeatMode(ValueAnimator.REVERSE);
        objectAnimator.start();
    }

    //判断是否为数字
    public static boolean isNubmer(String str) {
        Pattern pattern = Pattern.compile("-?[0-9]+\\.?[0-9]+");
        Matcher isNum = pattern.matcher(str);
        if (!isNum.matches()) {
            return false;
        }
        return true;
    }
    //从字符串转颜色
    private int GetColorValue(String paramColor){
        int PenColor= Color.WHITE;
        String StrPenColor=paramColor;
        if (StrPenColor.indexOf("#")==0){
            PenColor=Color.parseColor(StrPenColor);
        }else {
            if (isNubmer(StrPenColor)) {
                int testColor = Integer.parseInt(StrPenColor);
                int red = (testColor & 0xff0000) >> 16;
                int green = (testColor & 0x00ff00) >> 8;
                int blue = (testColor & 0x0000ff);
                PenColor = Color.rgb(red, green, blue);
            } else {
                if (StrPenColor.toLowerCase().equals("black") == true)
                    PenColor = Color.BLACK;
                if (StrPenColor.toLowerCase().equals("blue") == true)
                    PenColor = Color.BLUE;
                if (StrPenColor.toLowerCase().equals("yellow") == true)
                    PenColor = Color.YELLOW;
                if (StrPenColor.toLowerCase().equals("red") == true)
                    PenColor = Color.RED;
                if (StrPenColor.toLowerCase().equals("green") == true)
                    PenColor = Color.GREEN;
                if (StrPenColor.toLowerCase().equals("gray") == true)
                    PenColor = Color.LTGRAY;
                if (StrPenColor.toLowerCase().equals("white") == true)
                    PenColor = Color.WHITE;
            }
        }
        return PenColor;
    }
    //数据适配器，继承自BaseAdapter;
    private final class AndonAdapter extends BaseAdapter {
        private LayoutInflater inflater;
        public AndonAdapter(Context context) {
            inflater = (LayoutInflater) context
                    .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        }
        public  String TrnasValue(String params)
        {
            if ((params.toUpperCase()=="NULL".toUpperCase())||(params=="0")||(params=="0.0"))
                return "";
            else return params;
        }
        @Override
        public int getCount() {
            //固定行数;
            int count=totalItemCount;
            if (totalItemCount<CallList.length()) count=CallList.length();
            return count;
        }
        @Override
        public Object getItem(int position) {
            try {
                return CallList.getJSONArray(position);
            } catch (JSONException e)
            {
                e.printStackTrace();
                System.out.println("getItem取JSON数据出错!");
                return  null;
            }
        }
        @Override
        public long getItemId(int position) {
            return position;
        }
        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            View view = inflater.inflate(R.layout.andon_item, null, false);
            int pullVatListWidth=parent.getWidth();
            int pullVatListHeight=parent.getHeight();
            //一页显示6行;
            view.setLayoutParams(new ListView.LayoutParams((int)pullVatListWidth,(int)(pullVatListHeight/pageItemCount)));
            //转换分页码;
            int curPosition=position;
            if (curPosition< CallList.length()){
                try {
                    int textColor =Color.parseColor(CallList.optJSONObject(curPosition).getString("FontColor").toString());
                    TextView tv = view.findViewById(R.id.tv_grid_CallNo);// 显示文字
                    tv.setText(TrnasValue(CallList.optJSONObject(curPosition).getString("CallNo").toString()));
                    tv.setTextColor(textColor);
                    tv = view.findViewById(R.id.tv_grid_EmpName);// 显示文字
                    tv.setText(TrnasValue(CallList.optJSONObject(curPosition).getString("EmpName").toString()));
                    tv.setTextColor(textColor);
                    //if (position%2==0) tv.setBackground(drawable_itemA);else tv.setBackground(drawable_itemB);
                    tv = view.findViewById(R.id.tv_grid_CallType);// 显示文字
                    tv.setText(TrnasValue(CallList.optJSONObject(curPosition).getString("CallType").toString()));
                    tv.setTextColor(textColor);
                    //if (position%2==0) tv.setBackground(drawable_itemA);else tv.setBackground(drawable_itemB);
                    tv = view.findViewById(R.id.tv_grid_StateInfo);// 显示文字
                    tv.setText(TrnasValue(CallList.optJSONObject(curPosition).getString("StateInfo").toString()));
                    tv.setTextColor(textColor);
                    //if (position%2==0) tv.setBackground(drawable_itemA);else tv.setBackground(drawable_itemB);
                    tv = view.findViewById(R.id.tv_grid_WaitTime);// 显示文字
                    String CallTime = CallList.optJSONObject(curPosition).getString("CallTime").toString();
                    SimpleDateFormat sDateFormat=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                    Date curDate = sDateFormat.parse(CallTime);
                    Date endDate= new Date();
                    long from = sDateFormat.parse(CallTime).getTime();
                    long to = sDateFormat.parse(sDateFormat.format(endDate)).getTime();
                    float diff = (float) (1.0*(to-from)/(1000*60));
                    DecimalFormat df = new DecimalFormat("0.0");
                    tv.setText(df.format(diff)+"分");
                    tv.setTextColor(textColor);
                    //if (position%2==0) tv.setBackground(drawable_itemA);else tv.setBackground(drawable_itemB);
                } catch (ParseException e1) {
                    e1.printStackTrace();
                } catch (JSONException e1) {
                    e1.printStackTrace();
                }
            } else
            {
                TextView tv = view.findViewById(R.id.tv_grid_CallNo);// 显示文字
                tv.setText("");
                tv = view.findViewById(R.id.tv_grid_EmpName);// 显示文字
                tv.setText("");
                //if (position%2==0) tv.setBackground(drawable_itemA);else tv.setBackground(drawable_itemB);
                tv = view.findViewById(R.id.tv_grid_CallType);// 显示文字
                tv.setText("");
                //if (position%2==0) tv.setBackground(drawable_itemA);else tv.setBackground(drawable_itemB);
                tv = view.findViewById(R.id.tv_grid_StateInfo);// 显示文字
                tv.setText("");
                //if (position%2==0) tv.setBackground(drawable_itemA);else tv.setBackground(drawable_itemB);
                tv = view.findViewById(R.id.tv_grid_WaitTime);// 显示文字
                tv.setText("");
                //if (position%2==0) tv.setBackground(drawable_itemA);else tv.setBackground(drawable_itemB);
            }
            return view;
        }
    }


    //获取当前时间
    private String GetCurDateTime(){
        SimpleDateFormat sDateFormat=new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
        String  curDate= sDateFormat.format(new java.util.Date());
        return curDate;
    }


    //启动定时器;
    private void startTimer(){
        System.out.println(TAG+"----startTimer");
        //启动计时任务;
        if (waitDialog==null) {
            waitDialog=new ProgressDialog(getContext());
            waitDialog.setTitle("请稍等");
            waitDialog.setIndeterminate(true);
        }
        int spaceMiSec=5000;
        System.out.println("refreshSpaceSec:"+spaceMiSec);
        if (timer == null) {
            timer = new Timer();
        }
        //定时任务;
        if (timetask == null) {
            timetask = new TimerTask() {
                @Override
                public void run() {
                    //也可发消息，由Handler负责统一调度执行;
                    Message message = new Message();
                    message.what = MSG_Refresh;
                    handler.sendMessage(message);
                }
            };
            timer.schedule(timetask, 500, spaceMiSec);
        }
        System.out.println(TAG+"startTimer---------------------------------Start");
    }


    //停止计时器;
    private void stopTimer(){
        if (timer != null) {
            timer.cancel();
            timer = null;
        }
        if (timetask != null) {
            timetask.cancel();
            timetask = null;
        }
        if (waitDialog!=null) waitDialog.dismiss();
        System.out.println(TAG+"startTimer---------------------------------Start");
    }


    //通过消息来执行处理类程序,不更新UI则不一定需要通过这个;
    final Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            // TODO Auto-generated method stub
            // 根据消息ID来判断要做的事情
            int msgId = msg.what;
            switch (msgId) {
                case MSG_Refresh:
                    //刷新数据;
                    GetCallList();
                    //置卡片颜色;
                    setCardState(CurFontColor,CurCallNo,CurCallState);
                    //显示数据;
                    AndonAdapter andonAdapter=new AndonAdapter(getContext());
                    lv_andon.setAdapter(andonAdapter);
                    lv_andon.requestLayout();
                    lv_andon.invalidate();
                    break;
                default:
                    break;
            }
        }
    };

    @Override
    public void onClick(View v) {
        switch (v.getId()){

            default:
                break;
        }

    }



    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View root = inflater.inflate(R.layout.fragment_andon, container, false);
        InitView(root);//按钮初始化;
        System.out.println(TAG+"_onCreateView");
        return root;
    }

    //界面初始化;
    private void InitView(View v) {
        lv_andon=v.findViewById(R.id.lv_andon);
        img_Card=v.findViewById(R.id.img_Card);
        tv_CardCallNo =v.findViewById(R.id.tv_CardCallNo);
        tv_CardCallState=v.findViewById(R.id.tv_CardCallState);
        //语音播报;
        //voice_speed:最快语速1.5";
        //voice_pitch:最高音调2.0";
        textToSpeech=new TextToSpeech(getActivity(),new TTSListener());
        textToSpeech.setPitch(1.5f); // 在系统设置里也可以修改音调
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        stopTimer();
        stopMusic();
    }

    @Override
    public void onStart() {
        super.onStart();
        System.out.println(TAG+"----onStart");

    }

    @Override
    public void onPause() {
        super.onPause();
        stopTimer();
        stopMusic();
        System.out.println(TAG+"----onPause");
    }

    /**
     * 创建网络mp3
     * @return
     */
    public MediaPlayer createNetMp3(String fileName){
        String url=ServiceDir+"/"+fileName;
        System.out.println("音乐文件地址："+url);
        MediaPlayer mp=new MediaPlayer();
        try {
            mp.setDataSource(url);
        } catch (IllegalArgumentException e) {
            return null;
        } catch (IllegalStateException e) {
            return null;
        } catch (IOException e) {
            return null;
        }
        return mp;
    }

    //插放音乐;
    private void playMusic(String fileName){
        try {
            if(mediaPlayer==null) {
                mediaPlayer = createNetMp3(fileName);
                mediaPlayer.setLooping(true);
                //在播放音频资源之前，必须调用Prepare方法完成些准备工作
                mediaPlayer.prepare();
            }
            if(mediaPlayer!=null) {
                if (mediaPlayer.isPlaying()==false) mediaPlayer.start();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    //停止播放音乐
    private  void  stopMusic(){
        if(mediaPlayer!=null){
            mediaPlayer.stop();//停止播放
            mediaPlayer.release();//释放资源
            mediaPlayer=null;
        }
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if(hidden){
            stopTimer();
            stopMusic();
            System.out.println(TAG+"--onHiddenChanged--onPause");
        }else{
            System.out.println(TAG+"--onHiddenChanged--onStart");
        }
    }

}
